package com.datn.activity;

import java.util.ArrayList;

import com.datn.DataAccess.FavouriteDatabaseAdapter;
import com.datn.DataAccess.InstructionDatabaseAdapter;
import com.datn.utils.AlertCustom;
import com.datn.utils.BitmapUtils;
import com.datn.utils.GPSUtils;
import com.datn.utils.PreferenceUtils;
import com.datn.utils.ScreenSizeUtils;
import com.datn.utils.places.DirectionObject;
import com.datn.utils.places.JsonDirection;
import com.datn.utils.places.Place;
import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DirectionInstructionActivity extends Activity{

	private Place placeReceived;
	private GeoPoint startPosition, endPosition;
	private Context mContext;
	//private DirectionObject direction;
	private ListView lvInstruction;
	private ArrayList<String> instructions;
	private TextView tvName;
	private ImageView imgViewDirectionInstruction;
	public static final int PERCENT_DEFAUTL=80;
	private int width, height;
	public String placeIdSave;
	public Bitmap imageOffline;
	
	
	public GeoPoint getValueFromOtherActivity(){
		placeReceived = PreferenceUtils.getPlaceDetail();
		double latitude=0;
		double longitude=0;

		if(placeReceived !=null) {
			latitude = placeReceived.getLatitude();
			longitude = placeReceived.getLongtitude();
		}
		Log.v("DirectionInstruction", "Lat:"+placeReceived.getLatitude()+" Lng:"+ placeReceived.getLongtitude());
		return new GeoPoint((int)(latitude*1E6), (int)(longitude*1E6));
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.direction_instruction_view);
		PreferenceUtils.getInstance(this);
		
		lvInstruction = (ListView) findViewById(R.id.lvListDirectionInstruction);	
		tvName = (TextView) findViewById(R.id.tvNameDirectionInstruction);
		imgViewDirectionInstruction = (ImageView) findViewById(R.id.imgDirectionInstruction);
		mContext = this;
			
		ScreenSizeUtils size=new ScreenSizeUtils(mContext);
		size.setSizePercentFollowDevice(PERCENT_DEFAUTL);
		width = size.getWidth();
		height = size.getWidth();//size.getHeight();//getWidth for Square
		
		
		
		//Start and End Location
		startPosition = PreferenceUtils.getCurrentLocation();
		endPosition= getValueFromOtherActivity();	
		updateInstructionsToView(startPosition, endPosition);
	}
	
	
	public void updateInstructionsToView(final GeoPoint startLocation, final GeoPoint endLocation){
		new AsyncTask<String, Void, ArrayList<String>>() 
		{
			private ProgressDialog mProgressDialog;
			@Override
			protected void onPreExecute() 
			{
				mProgressDialog = new ProgressDialog(mContext);
				mProgressDialog.setMessage("Please Wait...");
				mProgressDialog.setCancelable(false);
				mProgressDialog.setIndeterminate(true);
				mProgressDialog.show();
			};

			@Override
			protected ArrayList<String> doInBackground(String... args) {
				// TODO Auto-generated method stub
				try {
					if (PreferenceUtils.isModeOnline()){
						JsonDirection jsonDirection=new JsonDirection(mContext, startLocation, endLocation);
						instructions = jsonDirection.getDirectionFromJSON().getInstructions();
					}
					else {
						
						FavouriteDatabaseAdapter adapterFavourite = new FavouriteDatabaseAdapter(mContext);
						adapterFavourite.open();
							String stLat = String.valueOf(placeReceived.getLatitude());
							String stLng = String.valueOf(placeReceived.getLongtitude());
							int place_id = adapterFavourite.getPlaceIdFromLatLng(stLat, stLng);
							if (place_id==-1) {
								place_id = adapterFavourite.getPlaceIdFromLatLngRecent(stLat, stLng);
							}
							String placeId = String.valueOf(place_id);
							placeIdSave = placeId;
							
							byte[] imageByteOffline = adapterFavourite.getImageFromLatLng(stLat, stLng);
							if (imageByteOffline!=null){
								if (imageByteOffline.length>0){
									imageOffline = BitmapUtils.getBitmapFromByteArray(imageByteOffline);
								}
							}
							
						adapterFavourite.close();
						Log.v("Search Place offline","Place Id for search:"+placeId);
						InstructionDatabaseAdapter adapter = new InstructionDatabaseAdapter(mContext);
						adapter.open();
							instructions = adapter.getListInstructionWithPlaceId(placeId);							
						adapter.close();
						
						
						
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					Toast.makeText(mContext, "Cannot parse JSON result", Toast.LENGTH_LONG).show();
				}
				return instructions;
			}

			@Override
			protected void onPostExecute(ArrayList<String> instructionTemp) 
			{
				if (mProgressDialog.isShowing()) 
				{
					mProgressDialog.dismiss();
				}
				if (instructionTemp != null) 
					{
						lvInstruction.setAdapter(new ArrayAdapter<String>(mContext, R.layout.item_instruction, instructions));
						if (PreferenceUtils.isModeOnline()){
							Bitmap bitmap = BitmapUtils.getDirectionStaticImageGoogleMap(startPosition, endPosition, width, height);
							if (bitmap!=null)
								imgViewDirectionInstruction.setImageBitmap(bitmap);
						}
						else{
							try {
								FavouriteDatabaseAdapter adapter =new FavouriteDatabaseAdapter(mContext);
								adapter.open();
								
								if (imageOffline!=null)
									imgViewDirectionInstruction.setImageBitmap(imageOffline);
								adapter.close();
								
							} catch (Exception e) {
								// TODO: handle exception
							}
							
						}
						
						tvName.setText(placeReceived.getName());
					} 
				else 
					{
						/*AlertCustom.showAlert(mContext, "Error", "Cannot receive direction");*/
						Toast.makeText(mContext, "Cannot receive direction", Toast.LENGTH_LONG).show();
					}

			};
		}.execute("...");
	}
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if (keyCode==KeyEvent.KEYCODE_BACK){
			processBack();
		}		
		return super.onKeyDown(keyCode, event);
	}
	
	public void processBack() {
		Intent intent=new Intent(this, DetailsPlaceActivity.class);
		startActivity(intent);
		finish();
	}

}
